//
//  ConversationViewController.m
//  HotWord
//
//  Created by Ji Qi on 12-6-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ConversationViewController.h"
#import "FriendInfoViewController.h"
#import "MessageManager.h"
#import "UserManager.h"
#import "ServiceHelper.h"
#import "Reachability.h"
#import "CacheData.h"

@interface ConversationViewController ()

@end

@implementation ConversationViewController
@synthesize dialogTableView;
@synthesize backBtn;
@synthesize toolbar;
@synthesize messageTextField;
@synthesize noDataView;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithUser:(User *)user
{
    self = [super init];
    if (self) {
        
        if (_user) {
            [_user release];
            _user = nil;
        }
        _user = [user retain];
        
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.dialogTableView.top = self.view.height;
    self.backBtn.alpha = 0;
    _messages = [[NSMutableArray alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    if (_messages) {
        [_messages release];
        _messages = nil;
    }
    _messages = [[[MessageManager sharedManager] getMessagesByUserId:_user.userId] retain];
    [self.dialogTableView reloadData];
    if ([_messages count] > 0) {
        
        [self.dialogTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_messages count] -1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
    else {
        if ([_messages count] <=0) {
            self.noDataView.hidden = NO;
        }
        else {
            self.noDataView.hidden = YES;
        }
    }
    //NOTIFICATION_RECEIVE_MESSAGE
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessageNotification) name:NOTIFICATION_RECEIVE_MESSAGE object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIView animateWithDuration:0.5 
                     animations:^{
                         self.backBtn.alpha = 1;
                         self.dialogTableView.top = 0;
                     }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.backBtn.alpha = 0;
                     }];
}


- (void)viewDidUnload
{
    [self setDialogTableView:nil];
    [self setBackBtn:nil];
    [self setToolbar:nil];
    [self setMessageTextField:nil];
    [self setNoDataView:nil];
    [self setSendingLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration 
                     animations:^{
                         self.toolbar.bottom = self.view.height - kbSize.height;
                     }];
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView animateWithDuration:duration 
                     animations:^{
                         self.toolbar.bottom = self.view.height;
                     }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Message *message = [_messages objectAtIndex:indexPath.row];
    if ([message.senderUserId isEqualToString:[UserManager sharedManager].currentUser.userId]) {
        
        static NSString *CellIdentifier = @"MessageToCell";
        
        MessageToCell *cell = (MessageToCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MessageToCell" owner:self options:nil] objectAtIndex:0];
        }
        [cell setMessage:message];
        return cell;
    }
    else {
        static NSString *CellIdentifier = @"MessageFromCell";
        
        MessageFromCell *cell = (MessageFromCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MessageFromCell" owner:self options:nil] objectAtIndex:0];
        }
        [cell setMessage:message];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    Message *message = [_messages objectAtIndex:indexPath.row];
    return [MessageToCell getCellHeightByContent:message.content] + 20;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_messages count];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)tapOnBackBtn:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)tapOnSendBtn:(id)sender {
    
    Reachability *reachAblility = [Reachability reachabilityForInternetConnection];
    [self.messageTextField resignFirstResponder];
	if (![reachAblility isReachable]){
        [[HTActivityIndicator currentIndicator] displayMessage:@"Bad Network"];
        return;
    }
    
    self.toolbar.userInteractionEnabled = NO;
    
    
    if (self.messageTextField.text && ![@"" isEqualToString:self.messageTextField.text]) {
  
        Message *message = [[[Message alloc] init] autorelease];
        message.content = self.messageTextField.text;
        message.senderUserId = [UserManager sharedManager].currentUser.userId;
        message.recevierUserId = _user.userId;
        message.timestamp = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
        message.dialogEmail = _user.email;
        message.dialogNickname = _user.nickname;
        message.isSentFailed = [NSNumber numberWithBool:NO];
        NSMutableArray *messages = [NSMutableArray array];
        [messages addObject:message];
        [[MessageManager sharedManager] addMessages:messages];
        if (_messages) {
            [_messages release];
            _messages= nil;
        }
        _messages = [[[MessageManager sharedManager] getMessagesByUserId:_user.userId] retain];
        [CacheData sharedData].tempMessage = message;
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
        [params setObject:_user.userId forKey:@"to"];
        [params setObject:self.messageTextField.text forKey:@"content"];
        self.sendingLabel.hidden = NO;
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeSendMsg WithParameters:params AndCallBackScope:self AndSuccessSel:@"sendMessageSuccess" AndFailedSel:@"sendMessageFailed"];
        self.messageTextField.text = nil;
        [self.dialogTableView reloadData];
        
        [self.dialogTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_messages count] -1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        if ([_messages count] <=0) {
            self.noDataView.hidden = NO;
        }
        else {
            self.noDataView.hidden = YES;
        }
    }
    else{
        self.toolbar.userInteractionEnabled = YES;
    }
}

- (void)sendMessageSuccess
{
    self.toolbar.userInteractionEnabled = YES;
    self.sendingLabel.hidden = YES;
}


- (void)sendMessageFailed
{
    self.toolbar.userInteractionEnabled = YES;
    self.sendingLabel.hidden = YES;
    [self.dialogTableView reloadData];
}

- (void)resendMessage:(Message *)message
{
    
    [CacheData sharedData].tempMessage = message;
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:nil message:@"是否重新发送" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil] autorelease];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        Reachability *reachAblility = [Reachability reachabilityForInternetConnection];
        
        if (![reachAblility isReachable]){
            [[HTActivityIndicator currentIndicator] displayMessage:@"Bad Network"];
            return;
        }
        
        self.toolbar.userInteractionEnabled = NO;
        [self.messageTextField resignFirstResponder];
    
        [[CacheData sharedData].tempMessage setIsSentFailed:[NSNumber numberWithBool:NO]];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
        [params setObject:_user.userId forKey:@"to"];
        [params setObject:[CacheData sharedData].tempMessage.content forKey:@"content"];
        
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeSendMsg WithParameters:params AndCallBackScope:self AndSuccessSel:@"sendMessageSuccess" AndFailedSel:@"sendMessageFailed"];
        [self.dialogTableView reloadData];
        
        [self.dialogTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_messages count] -1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        self.sendingLabel.hidden = NO;
    }
}

- (void)receiveMessageNotification
{
    
    if (_messages) {
        [_messages release];
        _messages= nil;
    }
    _messages = [[[MessageManager sharedManager] getMessagesByUserId:_user.userId] retain];
    
    [self.dialogTableView reloadData];
    
    [self.dialogTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_messages count] -1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    if ([_messages count] <=0) {
        self.noDataView.hidden = NO;
    }
    else {
        self.noDataView.hidden = YES;
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.messageTextField resignFirstResponder];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_user release];
    [_messages release];
    [dialogTableView release];
    [backBtn release];
    [toolbar release];
    [messageTextField release];
    [noDataView release];
    [_sendingLabel release];
    [super dealloc];
}
@end
